package cc.siyecao.fastdfs.downloader;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Download file by stream (download callback class)
 *
 * @author zhouzezhong & Happy Fish / YuQing
 * @version Version 1.11
 */
public class StreamDownloader implements Downloader {
    private OutputStream out;
    private long currentBytes = 0;

    public StreamDownloader(OutputStream out) {
        super();
        this.out = out;
    }

    /**
     * recv file content callback function, may be called more than once when the file downloaded
     *
     * @param fileSize file size
     * @param buff     data buff
     * @param data     data bytes
     * @return 0 success, return none zero(errno) if fail
     */
    @Override
    public int download(long fileSize, byte[] buff, int data) {
        try {
            out.write( buff, 0, data );
        } catch (IOException ex) {
            ex.printStackTrace();
            return -1;
        }
        currentBytes += data;
        if (this.currentBytes == fileSize) {
            this.currentBytes = 0;
        }
        return 0;
    }
}
